package com.lagou.edu.service;

import com.lagou.edu.bean.MailReturn;
import com.lagou.edu.bean.ToEmail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailException;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;

/**
 * @program: springcloud-web-one
 * @description: 发送邮件服务
 * @author: zhoushiduo
 * @create: 2021-03-22 15:27
 */

@Component
public class SendEmailService {

    @Autowired
    public JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    public String from;


    public MailReturn commonEmail(ToEmail toEmail) {
        //创建简单邮件消息
        SimpleMailMessage message = new SimpleMailMessage();
        //谁发的
        message.setFrom(from);
        //谁要接收
        message.setTo(toEmail.getTos());
        //邮件标题
        message.setSubject(toEmail.getSubject());
        //邮件内容
        message.setText(toEmail.getContent());
        MailReturn mailReturn = new MailReturn();
        try {
            mailSender.send(message);
            mailReturn.buildSuccess(toEmail.getTos(), "发送普通邮件成功");
        } catch (MailException e) {
            e.printStackTrace();
            mailReturn.buildFailure("普通邮件方失败");
        }
        return mailReturn;

    }
}